import type { MenuNodeType } from '../enums'
import type { ITab } from './tab'
import { defineStore } from 'pinia'
import useAppStore from './app'
import useMicroStore from './micro'
import useTabStore from './tab'

export interface IMenu {
  type: MenuNodeType
  name: string
  code: string
  projectCode: string
  appCode: string
  path: string
  visible: boolean
  href?: string
  iframeSrc?: string
  icon?: string
  flag?: string
  flagColor?: string
  fullscreen?: boolean
  component?: string
  children?: IMenu[]
  meta: Record<string, any>
}

interface IState {
  menus: IMenu[]
}

export const useMenuStore = defineStore('menu-store', {
  state: (): IState => ({
    menus: [],
  }),

  getters: {
    getMenus: state => state.menus,
  },

  actions: {
    setMenus(menus: IMenu[]) {
      this.menus = menus

      const {
        getTabs,
        addTab,
        updateTabs,
        removeAllTabs,
      } = useTabStore()

      if (getTabs.length > 0) {
        const { getAppCode } = useAppStore()
        const oldAppCode = getTabs[0].appCode
        if (oldAppCode !== getAppCode) {
          removeAllTabs()
          return
        }
      }

      if (getTabs.length === 0) {
        addTab(this.menus[0])
      }
      else {
        const tabCodes = getTabs.map(({ code }: ITab) => code)
        const tabs = this.menus
          .filter(({ code }: IMenu) => tabCodes.includes(code))
          .map((tab: ITab) => ({
            ...tab,
            query: getTabs.find(({ code }: ITab) => code === tab.code)?.query ?? {},
          }))

        updateTabs(tabs)

        const { getIsMicro } = useMicroStore()

        if (!getIsMicro) {
          const path = location.pathname.replace(import.meta.env.VITE_PUBLIC_PATH, '')
          const menu = menus.find((menu: IMenu) => menu.path === path)
          if (menu) {
            addTab(menu)
          }
        }
      }
    },

    updateMenus(menus: IMenu[]) {
      this.menus = menus
    },
  },

  persist: true,
})

export default useMenuStore
